package com.backstage.config;

import com.backstage.entity.Permission;
import com.backstage.entity.Role;
import com.backstage.entity.UserEntity;
import com.backstage.jwt.JWTToken;
import com.backstage.kits.CacheKits;
import com.backstage.kits.JwtKits;
import com.backstage.service.login.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;

/**
 * Created by cynic on 2018/4/9.
 */
public class JWTRealm extends AuthorizingRealm {

    private static Logger log = LoggerFactory.getLogger(JWTRealm.class);

    //用于用户查询
    @Autowired
    private LoginService loginService;

    @Value("${expireTime}")
    private Long expireTime;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    //角色权限和对应权限添加
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        //获取登录用户名
//        String userName = (String) principalCollection.getPrimaryPrincipal();
//        //查询用户名称
//        UserEntity userEntity = loginService.getUserByUserName(userName);
//        //添加角色和权限
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        for (Role role : userEntity.getRoles()) {
//            //添加角色
//            simpleAuthorizationInfo.addRole(role.getRoleName());
//            for (Permission permission : role.getPermissions()) {
//                //添加权限
//                simpleAuthorizationInfo.addStringPermission(permission.getPermission());
//            }
//        }
//        return simpleAuthorizationInfo;
        JWTToken token = (JWTToken) super.getAvailablePrincipal(principalCollection);

        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        List<Role> roles = token.getUserEntity().getRoles();
        log.warn("roles = " + roles.size());
        for (Role role : roles) {
            simpleAuthorInfo.addRole(role.getRoleName());
            log.warn("role name = " + role.getRoleName());
            List<Permission> permissions = role.getPermissions();
            log.warn("permissions = " + permissions.size());
            for (Permission permission : permissions) {
                log.warn("permission name = " + permission.getName());
                //添加权限
                simpleAuthorInfo.addStringPermission(permission.getName());
            }
        }
//        simpleAuthorInfo.addRole("user");
//        //添加权限
//        simpleAuthorInfo.addStringPermission("manage:init");
        return simpleAuthorInfo;
    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
//        if (authenticationToken.getPrincipal() == null) {
//            return null;
//        }
//        //获取用户信息
//        String userName = authenticationToken.getPrincipal().toString();
//        UserEntity userEntity = loginService.getUserByUserName(userName);
//        if (userEntity == null) {
//            //这里返回后会报出对应异常
//            return null;
//        } else {
//            //这里验证authenticationToken和simpleAuthenticationInfo的信息
//            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userEntity, userEntity.getPassword(), ByteSource.Util.bytes(userEntity.getSalt()), getName());
//            return simpleAuthenticationInfo;
//        }
        try {
            JWTToken token = (JWTToken) authenticationToken;
            String userName = (String) token.getPrincipal();
            // 未登录
            if (!token.isLogin()) {
//                String provider = token.getProvider();
//                //非第三方登录
//                if(provider==null) {
//                    userEntity = loginService.getUserByUserName(userName);
//                    //第三方登录
//                } else {
//                    //userEntity = loginService.selectByUnionid(principal);
//                }
                UserEntity userEntity = loginService.getUserByUserName(userName);
                if (userEntity == null)
                    throw new UnknownAccountException();//账号不存在
                token.setLogin(true);
                token.setToken(JwtKits.createToken("123456", userEntity));
                token.setUserEntity(userEntity);
                token.setExpireTime(expireTime);
                CacheKits.put(token.getToken(), token);
            }
            AuthenticationInfo authInfo = new SimpleAuthenticationInfo(token, token.getUserEntity().getPassword(), ByteSource.Util.bytes(token.getUserEntity().getSalt()), this.getName());
            return authInfo;
        } catch (Exception e) {
            throw new AccessTokenException(e);
        }
    }
}
